﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dapper;
using ErrCode.Model;

namespace ErrCode.Dal
{
    public class ProjectDal : BaseDal
    {
        private static readonly object LockObj = new object();
        /// <summary>
        /// 获取下一个系统编号
        /// author:xiaoy
        /// 2015-11-02 19:04:12 
        /// </summary>
        /// <returns></returns>
        public char GetNextSysCode()
        {
            char nextChar = '\0';
            string sql = "select SystemCode from systemIds order by id desc ";
            var maxChar = ErrCodeSysConnection.Query<char>(sql).FirstOrDefault();
            IEnumerator enumerator = CommonService.ProCode.GetEnumerator();
            while (enumerator.MoveNext())
            {
                if ((char)enumerator.Current == maxChar)
                {
                    enumerator.MoveNext();
                    nextChar = (char)enumerator.Current;
                    break;
                }
            }
            return nextChar;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="description"></param>
        /// <returns></returns>
        public int InsertSystem(string description)
        {
            lock (LockObj)
            {
                char systemCode = GetNextSysCode();
                string sql = "INSERT INTO systemIds (`systemcode`,`Description`) VALUES(@systemCode,@description);SELECT LAST_INSERT_ID();";
                return ErrCodeSysConnection.ExecuteScalar<int>(sql, new { systemCode, description });
            }
        }

        public List<SystemId> GetAllProjects()
        {
            string sql = "select * from systemIds";
            return ErrCodeSysConnection.Query<SystemId>(sql).ToList();
        }

        public SystemId GetSystemIdByCode(char code)
        {
            string sql = "SELECT * FROM systemids WHERE systemcode = @code;";
            return ErrCodeSysConnection.Query<SystemId>(sql, new { code }).FirstOrDefault();
        }
    }
}
